<template>
  <div
    class="v-editor-input"
    :class="{ 'g-pd-l-8': !selected }"
    @click.prevent
  >
    <HTMLViewer
      v-if="isAHtmlItem"
      :htmlText="inputvalue"
      :projectId="getProjectId()"
      @click.prevent
    />

    <div v-else>
      <el-input
        v-if="selected"
        v-model="inputvalue"
        type="textarea"
        class="_input_inputValue"
        :style="{ height: editDivHeight }"
        :disabled="row.readonly || isModelDisabled"
        @input="handleInput"
        @change="handelChange"
      ></el-input>
      <div
        v-else
        ref="showDiv"
      >
        {{ inputvalue }}
      </div>
    </div>

    <div
      v-if="selected && needHtmlEntry"
      :disabled="row.readonly || isModelDisabled"
      class="g-pd-r-4 img-btn"
    >
      <img
        src="statics/icons/app/iconmore.png"
        class="g-pointer"
        @click="handleClick()"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { modelService } from "@/modules/model/service";
import { ref, watch, inject, Ref, computed } from "vue";
import { propertyUtil } from "../../PropertyUtil";
import { PropertyRow, InputType } from "../../types";
import { BusEvent } from "@/constants/Enums";
import HTMLViewer from "@/modules/model/comps/common/HTMLViewer.vue";
import { desensitize } from "@/util/common";
import { GlobalNumberType } from "@/constants/StType";
import { htmlEditorWindow } from "@/modules/model/modals/htmlEditor";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

/**
 * 单行输入框
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  editDivHeight?: number;
  encrypted?: boolean;
  inputType?: InputType;
}>();

let showDiv = ref<HTMLElement>();
let editDivHeight = ref(props.editDivHeight ? Math.max(props.editDivHeight, 24) + "px" : "24px");
watch(
  () => props.selected,
  newVal => {
    // 从非编辑状态进入编辑状态，将显示时候的高度复制给编辑状态的div
    if (newVal && showDiv.value) {
      const height = Math.max(showDiv.value.clientHeight, 24) + "px";
      editDivHeight.value = height;
    }
  }
);

let inputvalue = ref<string>("");

const getProjectId = () => app.activeProject?.id || "";
watch(
  () => props.row.value,
  newVal => {
    let value = newVal;
    switch (props.row.key) {
      case "Customization::AttachedFile-file":
        value = JSON.parse(newVal as string)?.fileName;
        break;
      case "Customization::AttachedFile-size":
        value = ((newVal as number) / 1024).toFixed(1) + "KB";
        break;
      default:
        break;
    }
    inputvalue.value = props.encrypted ? desensitize(value as string) : (value as string); // 可能为字符串'null'
  },
  {
    immediate: true
  }
);

const handleInput = async () => {
  if (!props.inputType) return;
  switch (props.inputType) {
    case InputType.number:
      inputvalue.value = inputvalue.value.replace(/\D/g, "");
      break;
    case InputType.character:
      inputvalue.value = inputvalue.value.replace(/[^a-zA-Z]/g, "");
      break;
    case InputType.punctuationMark:
      inputvalue.value = inputvalue.value.replace(/[a-zA-Z0-9\s]/g, "");
      break;
    default:
      break;
  }
};

const handelChange = async () => {
  const dto = propertyUtil.getUpdatePropertyDtoByPropertyRow(props.row, app.activeProject!.id);
  dto.value = inputvalue.value;
  let res = await modelService.updateModelProperty(dto);
  if (res) {
    app.$bus.emit(BusEvent.REFRESH_PROPERTY, props.row.modelId);
  }
};

const isAHtmlItem = computed(() => {
  if (!propertyUtil.isHtmlTextProperty(props.row.key, props.row.dataType)) {
    return false;
  }
  if (typeof inputvalue.value === "string") {
    return inputvalue.value?.startsWith("<");
  } else {
    return false;
  }
});

const needHtmlEntry = computed(() => {
  if (props.row.key === GlobalNumberType["NumberPart-initialValue"]) {
    return false;
  }
  if (props.row.readonly || isModelDisabled?.value) {
    return false;
  }
  return propertyUtil.isHtmlTextProperty(props.row.key, props.row.dataType);
});

async function handleClick() {
  if (props.row.readonly || isModelDisabled?.value) {
    return;
  }
  await htmlEditorWindow
    .popup({
      projectId: getProjectId(),
      text: encodeURIComponent((props.row.value as string) || ""),
      modelId: props.row.modelId,
      modelIds: props.row.modelIds && props.row.modelIds.length ? [...props.row.modelIds] : undefined
    })
    .then(async res => {
      if (res.success) {
        inputvalue.value = res.value as string;
        handelChange();
      }
    })
    .catch((err: any) => err && console.error(err));
}
</script>
<style lang="scss">
.v-editor-input {
  position: relative;

  .img-btn {
    position: absolute;
    right: 2px;
    z-index: 99;
    // top:2px;
  }
  ._input_inputValue {
    overflow: hidden;
    height: 100%;
  }
  .el-textarea__inner {
    height: 100%;
    resize: none;
  }
  .el-textarea__inner:hover {
    box-shadow: none;
  }
}
</style>
